<template>
    <div class="content">
        <!--头部-->
        <div class="header-setting">
            <a-breadcrumb class="breadcrumb">
                <a-breadcrumb-item>
                    <a href="../main">首页</a>
                </a-breadcrumb-item>
                <a-breadcrumb-item>系统设置</a-breadcrumb-item>
                <a-breadcrumb-item>月卡配置</a-breadcrumb-item>
            </a-breadcrumb>
            <!--查询条件-->
            <div class="box-condition-body">
                <div class="box-condition-item">
                    <div style="margin: 0 50px">月卡名称</div>
                    <template>
                        <a-input
                                style="margin: 0 200px 0 50px" placeholder="月卡名称" v-model="inputCardName"
                                @change="selectChange"/>
                    </template>

                    <div style="margin: 0 50px">月卡类型</div>
                    <template>
                        <a-select style="width: 200px" v-model="inputType" :options="selectCardRangeOption"
                                  placeholder="月卡类型" @change="selectChange"/>
                    </template>
                </div>
            </div>
        </div>

        <!-- 表内容 -->
        <div class="box-form">
            <!--工具栏-->
            <div class="box-tool">
                <div></div>
                <div style="display: flex">
                    <a-button @click="addTap" icon="plus">添加配置</a-button>

                    <!-- 删除 -->
                    <template v-if="selectedRowKeys.length != 0">
                        <a-popconfirm
                                title="确认删除？" okText="确认" cancelText="取消"
                                @confirm="deleteClick" placement="topLeft">
                            <a-button icon="delete">删除</a-button>
                        </a-popconfirm>
                    </template>
                    <template v-else>
                        <a-button icon="delete" @click="deleteClick">删除</a-button>
                    </template>
                </div>
            </div>

            <!-- 弹窗 -->
            <a-modal
                    :title="title" v-model="dispatchPopupData.visible"
                    :confirmLoading="dispatchPopupData.loading"
                    @cancel="() => { this.hideDispatchPopup() }" @ok="addMonthCardConfig">

                <div class="flexCommon" style="justify-content: flex-start;margin: 20px 0;">
                    <a-col :span="6">待配置月卡</a-col>
                    <a-col :span="6">
                        <a-select style="margin: 0 50px 0 10px; width: 200px"
                                  placeholder="待配置月卡"
                                  optionFilterProp="children"
                                  @select="initParkData"
                                  v-model="selectCard"
                        >
                            <a-select-option v-for="p in cardInfo" :key="p.id">{{p.cardName}}
                            </a-select-option>
                        </a-select>
                    </a-col>
                </div>

                <a-row style="margin-top:0.5em">
                    <a-col :span="6">选择停车点</a-col>
                    <a-col :span="16">
                        <a-tree
                                v-model="selectParkIds"
                                checkable
                                :expanded-keys="expandedKeys"
                                :auto-expand-parent="autoExpandParent"
                                :selected-keys="selectedKeys"
                                :tree-data="parkPointList"
                                @expand="onExpand"
                                @select="onSelect"
                                @check ="onCheck"
                        />
                    </a-col>
                </a-row>
            </a-modal>

            <!--数据表格-->
            <div class="box-table">
                <a-table
                        rowKey="no"
                        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,columnWidth:'3.5%'}"
                        :columns="columns"
                        :dataSource="entryExitRecordList"
                        :pagination="pagination"
                        @change="tableTabSort"
                        bordered size="small"
                        :scroll="scroll">

                    <template slot="isValid" slot-scope="text">
                        <div v-if="text==0">无效</div>
                        <div v-if="text==1">有效</div>
                    </template>
                    <template slot="cardType" slot-scope="text">
                        <div v-if="text==1">自然月卡</div>
                        <div v-else>其它月卡</div>
                    </template>
                    <template slot="cardRange" slot-scope="text">
                        <div v-if="text==0">路外</div>
                        <div v-else-if="text==1">路内</div>
                    </template>
                </a-table>
            </div>
        </div>
    </div>
</template>

<script>
    import moment from 'moment';
    import AddPagesUtils from "../../utils/AddPagesUtils";
    import Constant from "../../utils/Constant";
    import MonthCardApi from "../../api/system/MonthCardManage";
    import CommonApi from "../../api/CommonApi";
    import ChargeSettingApi from '../../api/system/ChargeSettingApi';
    const columns = [
        {
            title: "月卡名称",
            dataIndex: "cardName",
            width: '8%',
        },
        {
            title: "月卡类型",
            dataIndex: "cardType",
            scopedSlots: {customRender: 'cardType'},
            width: '11%',
        },
        {
            title: "细粒度",
            dataIndex: "cardRange",
            scopedSlots: {customRender: 'cardRange'},
            width: '8%',
        },{
            title: "停车场",
            dataIndex: "parkName",
            width: '8%',
        },
        {
            title: "泊位名称",
            dataIndex: "truckSpaceName",
            width: '10%',
        },
        {
            title: "月卡开始时间",
            dataIndex: "startTime",
            width: '10%',
        },
        {
            title: "月卡结束时间",
            dataIndex: "endTime",
            width: '10%',
        },
        {
            title: "月卡描述",
            dataIndex: "description",
            width: "10%",
        },
    ];

    /*设备查询条件*/
    const conditionOfCard = {
        cardName: "",
        cardType: "",
        limit: "10",
        curr: "1"
    };

    export default {
        name: "MonthCardManage",

        data() {
            return {
                /*查询条件*/
                conditionOfCard,
                selectdevicevalidStatus: 2,
                inputCardName: '',
                inputType: '',
                selectCardRangeOption:[{"value":'',"label":"月卡类型"}, {"value":0,"label":"路外"},{"value":1,"label":"路内"}],
                /*当前选中的行数据*/
                entryExitRecordList: [],
                /*待配置月卡信息*/
                cardInfo:[],
                columns,
                selectId: -1,
                parks: [],
                deviceUploadUrl: Constant.TEMPLATEUPLOAD_URL,
                uploadHeaders: {authorization: JSON.parse(localStorage.getItem('userinfo')).data},

                /*分页插件*/
                pagination: {
                    showTotal: total => `共${total}条`,
                    total: 0,
                    defaultCurrent: 1,
                    showQuickJumper: true,
                    current: 1,
                    defaultPageSize: 10
                },

                /* 增加弹窗 */
                dispatchPopupData: {
                    visible: false,
                    loading: false
                },
                title:'添加月卡配置',
                selectCard:'',
                isValid:'',
                isValidOption:[{"value":0,"label":"无效"},{"value":1,"label":"有效"}],
                startTime:'',
                endTime:'',
                cardDescription:'',
                cardCharge:'',

                /*联动部分变量*/
                autoExpandParent:true,
                selectParkIds:[],
                expandedKeys:[],
                selectedKeys:[],
                parkPointList: [],

                /*时间日期*/
                momentArr: [],
                momentArrPop: [],

                /* 表单选择 */
                selectedRowKeys: [],            /* 选择key */
                /*表格固定头部*/
                scroll: {
                    y: 550,
                },
            }
        },

        mounted() {
            this.initData();
        },

        methods: {
            initData() {
                this.loadDeviceList();
                this.loadCardInfo();
                this.parkingPointTree();
            },

            /* ---------------- 外部表单操作 ---------------- */
            addTap() {
                let selectArray = this.getSelectArray();
                if(selectArray.length != 0) {
                    this.$message.error("请取消选中数据！");
                    return ;
                }

                this.dispatchPopupData.visible = true;
                this.dispatchPopupData.loading = false;
                this.title="添加月卡配置";
                this.isValid=1;
                this.startTime='';
                this.endTime='';
                this.momentArrPop[0] = null;
                this.momentArrPop[1] = null;
            },

            deleteClick() {
                let selectArray = this.getSelectArray();
                if(selectArray.length == 0) {
                    this.$message.error("请至少选中一个");
                    return ;
                }
                let value = JSON.stringify(selectArray.map(item => {
                    return { id: item.cardParkId}
                }))
                MonthCardApi.delMonthCardConfig(value)
                    .then(() => {
                        this.$message.success("删除成功！");
                        this.loadDeviceList();  // 重新加载
                    })
                    .catch((err) => {
                        let data = err.data, msg = err.msg;
                        this.$message(data || msg);
                    })
            },

            /* --------------- 设备查询条件 --------------- */
            /* 有效状态 */
            isvalidStatus(status) {
                this.selectdevicevalidStatus = status;
                this.loadDeviceList();
            },

            tableTabSort(pagination, filters, sorter) {
                let sortType = undefined;
                let sortField = undefined;
                if(sorter) {
                    let { order, columnKey } = sorter;
                    if(order === "descend") {
                        sortType = 0;
                    } else if(order == 'ascend') {
                        sortType = 1;
                    }

                    if(columnKey == 'sn') {
                        sortField = 0;
                    } else if(columnKey == 'device_name') {
                        sortField = 1;
                    } else if(columnKey == 'device_type') {
                        sortField = 2;
                    } else if(columnKey == 'is_valid') {
                        sortField = 3;
                    }
                }

                this.conditionOfCard.sortType = sortType;
                this.conditionOfCard.sortField = sortField;
                this.loadDeviceList(pagination.current);
            },

            resetQueryCondition() {
                this.inputCardName = "";
                this.inputType = "";
                this.conditionOfCard.cardType = [];
                this.clearSelectArray();
            },

            selectChange() {
                this.loadDeviceList()
            },

            /* --------------- 查询设备列表 --------------- */
            loadDeviceList(pageNum) {
                this.clearSelectArray();

                /* ---- condition ---- */
                let condition = this.conditionOfCard;
                condition.cardName = this.inputCardName;
                condition.cardType = this.inputType;
                condition.curr = pageNum || 1;

                /* ---- 查询 ---- */
                MonthCardApi.getMonthCardConfigInfoList(condition)
                    .then((data) => {
                        let { list, total, pageNum, pageSize } = data.data;
                        let array = list || [];
                        array = array.map((item, index) => {
                            return {...item, no: total - (pageNum - 1) * pageSize - index};
                        })
                        this.entryExitRecordList = array;
                        this.pagination.total = total;
                        this.pagination.current = pageNum;
                    })
                    .catch((err) => {
                        this.$message.error(err)
                    });
            },
            loadCardInfo() {
                /* ---- 查询 ---- */
                MonthCardApi.getMonthCardList()
                    .then((data) => {
                        this.cardInfo = data.data;
                    })
                    .catch((err) => {
                        this.$message.error(err)
                    });
            },

            /* ---------------- 选中处理 ------------------- */
            getSelectArray() {
                let entryExitRecordList = this.entryExitRecordList || [];
                let selectedRowKeys = this.selectedRowKeys;
                return entryExitRecordList.filter(item => {
                    return selectedRowKeys.filter(no => no == item.no).length > 0;
                })
            },

            clearSelectArray() {
                this.selectedRowKeys = [];
            },

            /* ----------------------------------------- */
            onSelectChange(selectedRowKeys) {
                this.selectedRowKeys = selectedRowKeys;
            },

            /* --------------- 内部弹窗 --------------- */
            seeLog_trigger(logUrl) {
                let url = encodeURI(logUrl).replace(/#/g, "%23");
                window.open(url);
            },

            downloadLogTrigger(logUrl) {
                let url = encodeURI(logUrl + '?attname=').replace(/#/g, "%23");
                window.open(url);
            },


            /*-----------------设备日志/设备心跳--------------*/
            /*点击遮罩层*/
            maskTap() {
                if (!this.maskClose) return;
                this.hideAddPages();
            },

            /*隐藏遮罩层*/
            hideAddPages() {
                this.isShowAddPages = false;
            },

            /*防止子类点击事件被穿透*/
            addPagesTap() {
            },

            doThis() {
            },

            /*时间按钮控制*/
            button_time(e, type) {
                //type 1 日志 2 心跳
                this.selectId = e;
                let momentStart;
                let momentEnd;
                switch (e) {
                    case 0:
                        momentStart = moment().startOf('day');
                        momentEnd = moment().endOf('day');
                        break;
                    case 1:
                        momentStart = moment().add('day', -1).startOf('day');
                        momentEnd = moment().add('day', -1).endOf('day');
                        break;
                    case 2:
                        momentStart = moment().week(moment().week()).startOf('week');
                        momentEnd = moment().week(moment().week()).endOf('week');
                        break;

                    case 3:
                        momentStart = moment().week(moment().week() - 1).startOf('week');
                        momentEnd = moment().week(moment().week() - 1).endOf('week');
                        break;
                    case 4:
                        momentStart = moment().month(moment().month()).startOf('month');
                        momentEnd = moment().month(moment().month()).endOf('month');
                        break;
                    default :
                        break;
                }
                this.momentArr[0] = momentStart;
                this.momentArr[1] = momentEnd;
                this.selectLogHeartbeatTrigger(type, true);
            },

            /*日期选择*/
            heartbeatOnChange(date) {
                this.selectId = -1;
                this.momentArr = date;
                if (date == undefined || date.length == 0) {
                    this.onOk(2);
                }
            },

            logOnChange(date) {
                this.selectId = -1;
                this.momentArr = date;
                if (date == undefined || date.length == 0) {
                    this.onOk(1);
                }
            },

            onOk(type) {
                this.selectId = -1;
                this.selectLogHeartbeatTrigger(type, true);
            },

            rangePickerValue() {
                return this.momentArr;
            },

            hideDispatchPopup() {
                this.dispatchPopupData.visible = false;
                this.selectCard='';
                this.selectParkIds = [];
            },
            //触发停车点数据
            initParkData(){
                let condition = {};
                condition.id = this.selectCard;
                MonthCardApi.getMonthCardRange(condition).then((data) => {
                    if (data.code === 2000) {
                        let range = data.data;
                        if (range === 0)
                        {
                            this.parkingPoint();
                        }
                        else
                        {
                            this.parkingPointTree();
                        }
                    }
                }).catch((err) => {
                    this.$message.warn('获取月卡粒度失败:'+err);
                    this.hideDispatchPopup();
                });
            },

            parkingPointTree() {
                ChargeSettingApi.pointTree()
                    .then((data) => {
                        this.parkPointList = data.data
                    })
                    .catch(error => this.$message.error("获取停车点泊位失败:"+error))
            },
            parkingPoint() {
                ChargeSettingApi.point()
                    .then((data) => {
                        this.parkPointList = data.data
                    })
                    .catch(error => this.$message.error("获取停车点失败:"+error))
            },
            onExpand(keys) {
                console.log('onExpand', keys);
                this.expandedKeys = keys;
                this.autoExpandParent = false;
            },
            // 点击复选框触发
            onCheck(keys) {
                console.log('onCheck', keys);
                this.selectParkIds = keys;
            },
            // 点击树节点触发
            onSelect(keys, info) {
                console.log('onselect', keys);
                this.selectParkIds = keys;
            },

            addMonthCardConfig() {
                let selectArray = this.getSelectArray();
                let condition = {};
                condition.id = this.selectCard;
                let imeiIdList=[];
                for(const i in this.selectParkIds){
                    if(this.selectParkIds[i].indexOf('-') ==-1){
                        imeiIdList.push(this.selectParkIds[i])
                    }
                }
                condition.imeiIdList=imeiIdList;
                if(condition.id === "" || condition.imeiIdList.length === 0) {
                    this.$message.error("请输入相关信息");
                    return ;
                }

                if(selectArray.length === 0)
                {
                    MonthCardApi.addMonthCardConfigInfo(condition).then((data) => {
                        if (data.code === 2000) {
                            this.$message.success("增加月卡配置操作成功");
                            this.initData();
                            this.hideDispatchPopup();
                        }
                        this.dispatchPopupData.visible = false;
                    }).catch((err) => {
                        this.$message.warn('增加月卡配置操作失败:'+err);
                        this.hideDispatchPopup();
                    });
                }
                else
                {
                    condition.cardParkId = selectArray[0].cardParkId;
                    condition.id = selectArray[0].id;
                    debugger;
                    MonthCardApi.updateMonthCardInfo(condition).then((data) => {
                        if (data.code === 2000) {
                            this.$message.success("编辑月卡操作成功");
                            this.initData();
                            this.hideDispatchPopup();
                        }
                        this.dispatchPopupData.visible = false;
                    }).catch((err) => {
                        this.$message.warn('编辑月卡操作失败:'+err);
                        this.hideDispatchPopup();
                    });
                }
            },
            setTime(fmt) {
                const time = new Date(fmt);
                const Y = time.getFullYear()
                const M = (time.getMonth() + 1).toString().padStart(2, '0')
                const D = time.getDate().toString().padStart(2, '0')
                const h = time.getHours().toString().padStart(2, '0')
                const m = time.getMinutes().toString().padStart(2, '0')
                const s = time.getSeconds().toString().padStart(2, '0')
                return `${Y}-${M}-${D} ${h}:${m}:${s}`
            },
            onOkPop(value) {
                this.momentArrPop = value;
                if (this.momentArrPop != undefined && this.momentArrPop.length != 0) {
                    this.startTime = this.setTime(this.momentArrPop[0]);
                    this.endTime = this.setTime(this.momentArrPop[1]);
                }
            },
            onChangePop(dates) {
                this.momentArrPop = dates;
            },
            rangePickerValuePop() {
                return this.momentArrPop;
            },
        },
    }
</script>

<style scoped>
    /*组件样式*/
    /*文本框*/
    .ant-input {
        width: 200px;
        margin: 0 8px 8px 0;
    }

    .clickRowStyl {
        background-color: #C1E0FD;
    }

    .content {
        width: 100%;
        height: 100%;
    }

    .header-setting {
        width: 100%;
        height: 120px;
        background: #fff;
    }

    .header-setting .breadcrumb {
        margin-left: 41px;
        padding-top: 15px;
    }

    /* 表单 */
    .box-form {
        padding-left: 40px;
        padding-right: 40px;
        min-height: 705px;
        background: #fff;
        margin-top: 8px;
    }

    .box-form .box-tool {
        padding-top: 11px;
        margin: 8px 0;
        width: 100%;
        /* flex */
        display: flex;
        align-items: center;
        justify-content: space-between;
    }


    .box-condition-item {
        display: flex;
        align-items: center;
        min-width: 1500px;
        margin-top: 10px;
        margin-bottom: 10px;
        padding: 5px 0;
    }

    .button_online {
        margin-left: 62px;
        display: flex;
    }

    .button_online button {
        margin-right: 10px;
    }

    .box-tool button {
        margin-right: 10px;
    }

    /*-----------------设备日志/设备心跳--------------*/
    .box-form-others {
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.6);
    }

    .box-form-others .form {
        width: 970.5px;
        height: 500px;
        padding-bottom: 20px;
        background: #fff;
        border-radius: 10px;
        /*max-height: ;*/

        position: fixed;
        left: 50%;
        top: 15%;
        transform: translate(-50%, 0);
        /* flex */
        display: flex;
        align-items: flex-start;
        flex-direction: column;
    }

    .box .box-item {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 5px 5px 20px 5px;
    }

    .button_time button {
        margin-left: 10px;
    }


</style>
